"""
@Description :   DINO-X 模型 API
@Author      :   tqychy 
@Time        :   2025/08/24 16:09:48
"""
from api_key import api_key
from dds_cloudapi_sdk import Client, Config
from dds_cloudapi_sdk.tasks.v2_task import create_task_with_local_image_auto_resize


class DinoX_API:
    def __init__(self, *args, model_path):
        self.cfg, self.logger = args
        config = Config(api_key("dinox"))
        self.model_path = model_path
        self.model = Client(config)

    def __call__(self, inputs):
        task = create_task_with_local_image_auto_resize(
            api_path=self.model_path,
            api_body_without_image=inputs[0],
            image_path=inputs[1],
        )
        self.model.run_task(task)
        response = task.result
        response = response["objects"]
        if len(response) == 0:
            raise ValueError("DINO-X 模型未检测到目标")
        return str(response[0]["bbox"]) if self.cfg.EVAL.TYPE == "rec" else response

    @staticmethod
    def make_prompt(image_path, sentence, category, mode):
        if mode == "rec":
            prompt = sentence
        elif mode == "detect":
            prompt = category
        else:
            raise ValueError(f"Unknown task type! {mode}")
        
        api_body = {
            "model": "DINO-X-1.0", # DINO-XSeek-1.0
            "prompt": {
                "type":"text",
                "text":prompt
            },
            "targets": ["bbox"],
            "bbox_threshold": 0.25,
            "iou_threshold": 0.8,
        }
        return (api_body, image_path)
    
    @staticmethod
    def covert_formatted_bbox(bbox, image_shape):
        """
        将 [x1, y1, x2, y2] 格式的 bbox 转换成 [x_min, y_min, width, height] 格式的​
        """
        x1, y1, x2, y2 = bbox
        x_min = min(x1, x2)
        y_min = min(y1, y2)
        width = max(x1, x2) - x_min
        height = max(y1, y2) - y_min
        return [x_min, y_min, width, height]